package interviewOfStream;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/*
 * Author: JacksonCoder
 * FileName: StreamExample
 * Version: 1.0.0
 */
public class StreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        //过滤和转换
        List<Integer> squareEvens = numbers.stream()
                .filter(n -> n % 2 == 0).
                map(n -> n * n).collect(Collectors.toList());

        System.out.println(squareEvens);

        //并行流：提高性能
        int sum = numbers.parallelStream()
                .mapToInt(Integer::intValue)
                .sum();
        System.out.println("Sum: " + sum);

        // 聚合操作： reduce
        int total = numbers.stream()
                .reduce(0,(a,b)-> a+b); // 对元素进行累加
        System.out.println("total: " + total);

        EmployeeExample();
    }

    static class Employee{
        String name;
        double salary;

        Employee(String name, double salary){
            this.name = name;
            this.salary = salary;
        }

        @Override
        public String toString(){
            return name + " : " + salary;
        }

        public static double salary(Object o) {
            return ((Employee)o).salary;
        }
    }

    public static void EmployeeExample(){

        List<Employee> employees = Arrays.asList(
                new Employee("Alice", 11000),
                new Employee("Alen", 12000),
                new Employee("Alex", 13000),
                new Employee("Tom", 4000)
        );

        employees.stream()
                .filter(e -> e.salary > 5000)   // 过滤工资大于5000的员工
                .sorted(Comparator.comparingDouble(Employee::salary).reversed()) // 按工资降序排序
                .forEach(System.out::println);

    }
}
